#!/bin/bash

# MySQL 用户名
USER="root"

# MySQL 密码
PASSWORD="123456"

# MySQL 主机
HOST="localhost"

# SQL 文件所在目录
SQL_DIR="/home/mysql"

# 遍历目录中的所有 .sql 文件
for SQL_FILE in "$SQL_DIR"/*.sql; do
    if [ -f "$SQL_FILE" ]; then
        # 从文件名提取前缀英文部分（去掉日期和扩展名）
        DB_NAME=$(basename "$SQL_FILE" .sql | cut -d'_' -f1)

        # 创建数据库
        echo "Creating database $DB_NAME..."
        mysql -u$USER -p$PASSWORD -h$HOST -e "CREATE DATABASE IF NOT EXISTS \`$DB_NAME\`;"

        # 导入SQL文件到创建的数据库
        echo "Importing $SQL_FILE into $DB_NAME..."
        mysql -u$USER -p$PASSWORD -h$HOST "$DB_NAME" < "$SQL_FILE"

        echo "$SQL_FILE has been imported into $DB_NAME."
    else
        echo "No SQL files found in $SQL_DIR"
    fi
done

echo "All SQL files have been imported into their respective databases."
